package com.znzz.course.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.znzz.course.R;
import com.znzz.course.entity.Course;
import com.znzz.course.entity.Student;
import com.znzz.course.util.db.CourseDao;
import com.znzz.course.util.db.StudentDao;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ScheduledExecutorService;

/**
 * 我的模块功能--基本信息、修改头像、退出登陆
 */
public class MyInformationActivity extends AppCompatActivity {
    //当前头像
    private de.hdodenhof.circleimageview.CircleImageView icon;
    // 头像Bitmap
    private Bitmap head;
    // sd路径
    private static String head_path = "sdcard/myHead/";
    //定时调度机制
    private ScheduledExecutorService scheduledExecutorService;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;

    //底部视图
    private ImageView imageView1,imageView2,imageView3;
    private LinearLayout layout1,layout2,layout3;
    //退出登陆
    private Button btn_exit;
    //基本信息TextView视图显示
    private TextView tv_name,tv_sex,tv_major,tv_phone,tv_lable,tv_collage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_information);
        //获取头像
        icon = (de.hdodenhof.circleimageview.CircleImageView) findViewById(R.id.icon_image);
        initView();
        StudentDao studentDao = new StudentDao(MyInformationActivity.this);
        //获取学生信息
        Student student = studentDao.loadData();
        if (student.getStudentId()==null||student.getPhone()==null){
            Toast.makeText(MyInformationActivity.this,"请绑定学生信息",Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(MyInformationActivity.this,MainActivity.class);
            startActivity(intent);
        }else{
            fillTVXX(student);
        }
        //退出登陆
        btn_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sharedPreferences = getSharedPreferences("userInfo", 0);
                SharedPreferences sharedPreferences1 = getSharedPreferences("studentInfo",0);
                if (sharedPreferences!=null){
                    editor = sharedPreferences.edit();
                    editor.clear();
                    editor.commit();
                }
                if (sharedPreferences1!=null){
                    editor = sharedPreferences1.edit();
                    editor.clear();
                    editor.commit();
                }
                /**
                 * 删除本地数据的课程信息和学生信息
                 */
                CourseDao courseDao = new CourseDao(MyInformationActivity.this);
                courseDao.deleteAllCourse();
                StudentDao studentDao1 = new StudentDao(MyInformationActivity.this);
                studentDao1.deleteStudent();
                Intent intent5 = new Intent(MyInformationActivity.this, LoginStudentActivity.class);
                startActivity(intent5);
                finish();
            }
        });
        layout2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyInformationActivity.this,MainActivity.class);
                startActivity(intent);
            }
        });
        layout1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyInformationActivity.this,IndexActivity.class);
                startActivity(intent);
            }
        });
    }

    //回调函数（如今需要从A的界面跳转到B（C）的界面执行相应的操作。操作执行完毕之后，从B（C）的界面跳转回A的界面，或许还会返回一些数据交给A处理）
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            //从相册里面取相片的返回结果
            case 1:
                if (resultCode == RESULT_OK) {
                    cropPhoto(data.getData());// 裁剪图片
                }
                break;
            //调用系统裁剪图片后
            case 2:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    head = extras.getParcelable("data");
                    if (head != null) {
                        setPicToView(head);// 保存在SD卡中
                        icon.setImageBitmap(head);// 用CicleImageView显示出来
                    }
                }
                break;
            //调用拍摄功能
            case 3:
                if (resultCode == RESULT_OK) {
                    File temp = new File(Environment.getExternalStorageDirectory() + "/head.jpg");
                    cropPhoto(Uri.fromFile(temp));// 裁剪图片
                }
                break;

            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //修改头像OnClick()/在header.xml中
    public void change_image(View v){
        showTypeDialog();
    }

    //修改背景的方法
    private void showTypeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MyInformationActivity.this);
        final AlertDialog dialog = builder.create();
        //获取调用图库方法页面
        final View change = LayoutInflater.from(this).inflate(R.layout.change_user_image, null);
        TextView select_gallery = (TextView) change.findViewById(R.id.select_gallery);
        //change_user_image按钮
        select_gallery.setOnClickListener(new View.OnClickListener() {// 在相册中选取
            @Override
            public void onClick(View v) {
                //图片调用图库intent
                Intent changepho = new Intent(Intent.ACTION_PICK, null);
                //打开系统相册，获取图片进行扫描操作
                changepho.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(changepho,1);
                dialog.dismiss();
            }
        });
        dialog.setView(change);
        dialog.show();
    }

    //调用系统的裁剪功能
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高    -------main(960,1706)
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 2);
    }

    //将传递的数据保存到SD卡中
    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            return;
        }
        FileOutputStream b = null;
        String fileName;
            File file = new File(head_path);
            file.mkdirs();// 创建文件夹
            fileName = head_path + "head.jpg";// 图片名字
        try {
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭流
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void initView(){
        layout2 = findViewById(R.id.layout2);
        layout1 = findViewById(R.id.layout1);
        btn_exit = findViewById(R.id.btn_exit);
        tv_name = findViewById(R.id.tv_name);
        tv_collage =findViewById(R.id.tv_collage);
        tv_lable = findViewById(R.id.tv_lable);
        tv_sex =findViewById(R.id.tv_sex);
        tv_major = findViewById(R.id.tv_major);
        tv_phone = findViewById(R.id.tv_phone);
    }

    //将学生数据显示到Information页面
    public void fillTVXX(Student student){
        tv_name.setText(student.getName()+"");
        tv_phone.setText(student.getPhone()+"");
        tv_major.setText(student.getMajor()+"");
        tv_sex.setText(student.getSex()+"");
        tv_collage.setText(student.getCollage()+"");
    }
}